package com.cch.cooperation.api.common.config;

import com.cch.cooperation.api.auth.interceptors.UserDeviceInterceptor;
import com.cch.cooperation.api.auth.service.UserDeviceServiceImpl;
import com.cch.cooperation.api.common.sign.SignValidInterceptor;
import com.cch.cooperation.api.common.session.RedisSessionPool;
import com.cch.cooperation.common.web.interceptors.AuthorityInterceptor;
import com.cch.cooperation.common.web.interceptors.CORSInterceptor;
import com.cch.cooperation.common.web.session.SessionManager;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 后端服务配置
 *
 * @author cch
 */
@Configuration
public class AdminConfiguration {

    @Resource
    private RedisSessionPool sessionPool;
    @Resource
    private RedissonClient redissonClient;

    @Bean
    public SessionManager userSessionManager() {
        return new SessionManager(sessionPool);
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer(SessionManager sessionManager, UserDeviceServiceImpl userDeviceService) {
        return new WebMvcConfigurer() {

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new CORSInterceptor())
                        .addPathPatterns("/**");
                registry.addInterceptor(new SignValidInterceptor(redissonClient))
                        .addPathPatterns("/**");
                registry.addInterceptor(new AuthorityInterceptor(sessionManager))
                        .addPathPatterns("/api/**")
                        .excludePathPatterns(
                                "/api/auth/user/login*",
                                "/api/support/file/**",
                                "/api/support/app/info/**",
                                "/api/support/sms/**"
                        );
                registry.addInterceptor(new UserDeviceInterceptor(sessionManager, userDeviceService))
                        .addPathPatterns("/api/**");
            }
        };
    }
}
